<template>
  <div>
    <!--面包屑模块-->
    <el-breadcrumb separator-class="el-icon-arrow-right" style="padding: 10px">
      <el-breadcrumb-item :to="{ path: '/manage/' + this.id }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>系统角色管理</el-breadcrumb-item>
    </el-breadcrumb>
    <!--卡片视图区域-->
    <el-card>
      <!-- 添加角色按钮 -->
      <el-row>
        <el-col :span="4">
          <el-button type="primary" @click="showAddRoleDialog">添加角色</el-button>
        </el-col>
      </el-row>
      <!-- 表格显示区 -->
      <el-table :data="roleList" border style="width: 100%; margin-top: 15px" stripe>
        <el-table-column prop="id" label="角色ID" width="100"></el-table-column>
        <el-table-column prop="name" label="角色名称" width="150"></el-table-column>
        <el-table-column prop="description" label="角色描述"></el-table-column>
        <el-table-column label="操作" width="200">
          <template slot-scope="scope">
            <el-tooltip effect="dark" content="编辑角色" placement="top" :enterable="false">
              <el-button type="primary" size="mini" icon="el-icon-edit" @click="editRole(scope.row)"></el-button>
            </el-tooltip>
            <el-tooltip effect="dark" content="删除角色" placement="top" :enterable="false">
              <el-button 
                type="danger" 
                size="mini" 
                icon="el-icon-delete" 
                @click="deleteRole(scope.row)"
                :disabled="scope.row.id <= 2">
              </el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 添加角色对话框 -->
    <el-dialog title="添加角色" :visible.sync="addRoleDialogVisible" width="50%" @close="addRoleDialogClosed">
      <el-form :model="addRoleForm" :rules="roleFormRules" ref="addRoleFormRef" label-width="100px">
        <el-form-item label="角色ID" prop="id">
          <el-input v-model.number="addRoleForm.id" type="number"></el-input>
        </el-form-item>
        <el-form-item label="角色名称" prop="name">
          <el-input v-model="addRoleForm.name"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="description">
          <el-input v-model="addRoleForm.description" type="textarea" :rows="3"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addRoleDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addRole">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 编辑角色对话框 -->
    <el-dialog title="编辑角色信息" :visible.sync="editRoleDialogVisible" width="50%" @close="editRoleDialogClosed">
      <el-form :model="editRoleForm" :rules="roleFormRules" ref="editRoleFormRef" label-width="100px">
        <el-form-item label="角色ID">
          <el-input v-model="editRoleForm.id" disabled></el-input>
        </el-form-item>
        <el-form-item label="角色名称" :rules="{ required: true, message: '请输入角色名称', trigger: 'blur' }" 
          :disabled="editRoleForm.id <= 2">
          <el-input v-model="editRoleForm.name" :disabled="editRoleForm.id <= 2"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="description">
          <el-input v-model="editRoleForm.description" type="textarea" :rows="3"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editRoleDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitEditRoleForm">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'RoleManagement',
  data() {
    return {
      id: sessionStorage.getItem('userID'),
      // 角色列表
      roleList: [],
      // 添加角色对话框
      addRoleDialogVisible: false,
      // 添加角色表单
      addRoleForm: {
        id: '',
        name: '',
        description: ''
      },
      // 编辑角色对话框
      editRoleDialogVisible: false,
      // 编辑角色表单
      editRoleForm: {
        id: '',
        name: '',
        description: ''
      },
      // 角色表单验证规则
      roleFormRules: {
        id: [
          { required: true, message: '请输入角色ID', trigger: 'blur' },
          { type: 'number', message: '角色ID必须为数字', trigger: 'blur' }
        ],
        name: [
          { required: true, message: '请输入角色名称', trigger: 'blur' },
          { min: 2, max: 20, message: '角色名称长度在2到20个字符之间', trigger: 'blur' }
        ],
        description: [
          { required: true, message: '请输入角色描述', trigger: 'blur' },
          { max: 100, message: '描述长度不能超过100个字符', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.getRoleList()
  },
  methods: {
    // 获取角色列表
    async getRoleList() {
      try {
        const { data: res } = await this.$http.get('/role/all')
        if (res.code === 200) {
          this.roleList = res.data
        } else {
          this.$message.error('获取角色列表失败: ' + res.msg)
        }
      } catch (error) {
        this.$message.error('获取角色列表失败: ' + error.message)
      }
    },
    
    // ===== 添加角色相关方法 =====
    showAddRoleDialog() {
      this.addRoleDialogVisible = true
    },
    
    addRoleDialogClosed() {
      this.$refs.addRoleFormRef.resetFields()
    },
    
    addRole() {
      this.$refs.addRoleFormRef.validate(async valid => {
        if (!valid) return
        
        try {
          const { data: res } = await this.$http.post('/role/add', this.addRoleForm)
          if (res.code === 200) {
            this.$message.success('添加角色成功')
            this.addRoleDialogVisible = false
            this.getRoleList()
          } else {
            this.$message.error('添加角色失败: ' + res.msg)
          }
        } catch (error) {
          this.$message.error('添加角色失败: ' + error.message)
        }
      })
    },
    
    // ===== 编辑角色相关方法 =====
    editRole(role) {
      this.editRoleForm = JSON.parse(JSON.stringify(role)) // 深拷贝
      this.editRoleDialogVisible = true
    },
    
    editRoleDialogClosed() {
      this.$refs.editRoleFormRef.resetFields()
    },
    
    submitEditRoleForm() {
      this.$refs.editRoleFormRef.validate(async valid => {
        if (!valid) return
        
        try {
          const { data: res } = await this.$http.put('/role/update', this.editRoleForm)
          if (res.code === 200) {
            this.$message.success('更新角色成功')
            this.editRoleDialogVisible = false
            this.getRoleList()
          } else {
            this.$message.error('更新角色失败: ' + res.msg)
          }
        } catch (error) {
          this.$message.error('更新角色失败: ' + error.message)
        }
      })
    },
    
    // ===== 删除角色相关方法 =====
    deleteRole(role) {
      // 系统内置角色不允许删除
      if (role.id <= 2) {
        this.$message.warning('系统内置角色不允许删除')
        return
      }
      
      this.$confirm('此操作将永久删除该角色, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          const { data: res } = await this.$http.delete(`/role/delete/${role.id}`)
          if (res.code === 200) {
            this.$message.success('删除角色成功')
            this.getRoleList()
          } else {
            this.$message.error('删除角色失败: ' + res.msg)
          }
        } catch (error) {
          this.$message.error('删除角色失败: ' + error.message)
        }
      }).catch(() => {
        this.$message.info('已取消删除')
      })
    }
  }
}
</script>

<style scoped lang="less">
.el-card {
  box-shadow: 0 1px 1px rgba(0, 0, 0, 0.15) !important;
  margin-bottom: 20px;
}

.el-button {
  margin-right: 10px;
}
</style>
